package hqb.dev.webdeploy.flow;

import cn.hutool.core.io.FileUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.hutool.json.JSONObject;

import javax.sql.DataSource;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.List;

/**
 * mysql执行步骤,逐行执行sql文件中的sql语句
 *
 * @author HQB--2024-04-22
 **/
public class FlowStepMysql extends FlowStep {

    private final File sqlFile;
    private final DataSource dataSource;

    public FlowStepMysql(String name, String desc, JSONObject y, File unzipDir) {
        super(name, desc);
        String path = y.getStr("path");
        this.sqlFile = new File(unzipDir, path);
        JSONObject db = y.getJSONObject("db");
        this.dataSource = new SimpleDataSource(
                String.format("jdbc:mysql://%s:%s/%s?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false",
                        db.getStr("host"),
                        db.getInt("port"),
                        db.getStr("database")
                ),
                db.getStr("username"),
                db.getStr("password")
        );
    }

    @Override
    public void execute() {
        List<String> strings = FileUtil.readLines(sqlFile, StandardCharsets.UTF_8);
        Db use = DbUtil.use(this.dataSource);
        for (String s : strings) {
            if (s.trim().startsWith("--") || s.trim().isEmpty()) continue;
            try {
                use.execute(s);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        DbUtil.close(this.dataSource);
    }
}
